package org.example.bighomework.TC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
//业务层实现
@Service
public class TCServiceimpl implements TCService{
    @Autowired
    private TCRepository tcRepository;
    @Override
    public List<TC> getAllTC() {
        return tcRepository.findAll();
    }
    @Override
    public void saveTC(TC tc) {
        this.tcRepository.save(tc);
    }
    @Override
    public TC getTCById(TnoCnoPK id) {
        Optional<TC> optional = tcRepository.findById(id);
        TC tc = null;
        // 如果存在指定id
        if (optional.isPresent()) {
            // 从Optional对象中获取对象
            tc = optional.get();
        } else {
            // 否则抛出运行时异常
            throw new RuntimeException("找不到ID :: " + id);
        }
        return tc;
    }
    @Override
    public void deleteTCById(TnoCnoPK id) {
        this.tcRepository.deleteById(id);
    }
    @Override
    public List<TC> findByTno(String Tno) {
        List<TC> tcs=tcRepository.findAllByTno(Tno);
        return tcs;
    }
    @Override
    public void updateTC(TC tc) {
        this.tcRepository.save(tc);
    }
    @Override
    public Page<TC> findPaginated(int pageNo, int pageSize, String sortField, String sortDirection) {
        //设置排序参数，升序ASC/降序DESC
        Sort sort = sortDirection.equalsIgnoreCase(Sort.Direction.ASC.name())
                ? Sort.by(sortField).ascending()
                : Sort.by(sortField).descending();
        //根据页号/每页记录数/排序依据返回某指定页面数据。
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, sort);
        //使用jpa提供的findAll函数，传入pageable参数。
        return this.tcRepository.findAll(pageable);
    }
}